<template>
  <div id="app" >
    <el-container>
      <el-main class="center" style="height: 800px">
        <el-row >
          <el-col :span="Number('5')">

            <el-card style="height: 500px;width:180px;float: right">
              <!-- <p @click="location.href='personal.html'">个人信息</p>-->
              <p style="color: #42b983;font-size:20px;text-align: center">稿件管理</p> <!--#2c3e50-->
              <hr>
              <br>
              <br>
              <a href="/frontEnd/homePage" style="font-size:17px;
              display: flex; align-items: center; justify-content: center;"
                 onmouseover="this.style.color='#42b983';" onmouseout="this.style.color='black';">返回主页</a>
              <br>
              <br>
              <a href="/frontEnd/user/homePage" style="font-size:17px;
              display: flex; align-items: center; justify-content: center;"
                 onmouseover="this.style.color='#42b983';" onmouseout="this.style.color='black';">返回个人中心</a>
            </el-card>
          </el-col>


          <el-col :span="Number('17')">
            <el-card>
              <!--标签页卡开始-->
              <el-tabs style="padding-top:15px;padding-left:15px" v-model="activeTab"  type="card"> <!--@tab-click="handleClick"-->
                <el-tab-pane :disabled="isEdit"  label="上传图文" name="1"></el-tab-pane>
                <!--<el-tab-pane :disabled="isEdit" label="上传视频" name="2"></el-tab-pane>-->
                <!--<el-tab-pane :disabled="isEdit" label="游戏" name="3"></el-tab-pane>-->
              </el-tabs>
              <!--标签页卡结束-->

              <!--发布文章表单开始-->
              <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">


                <br>
                <el-form-item label="文章标题" prop="title">
                  <el-input style="width: 600px" v-model="ruleForm.title"
                            placeholder="填写标题,可能会有更多赞哦~"></el-input>
                </el-form-item>
                <br>

                <el-form-item label="文章分类" prop="categoriesId">
                  <el-select style="width: 600px" v-model="ruleForm.categoriesId"
                             placeholder="请选择文章分类吧~">
                    <el-option v-for="(category,index) in categoryOptions"
                               :key="index"
                               :label="category.name" :value="index"></el-option>
                  </el-select>
                </el-form-item>
                <br>

                <el-form-item label="添加地点" prop="articleLocation">
                  <el-select style="width: 600px" v-model="ruleForm.articleLocation"
                             placeholder="请添加发布地点~">
                    <el-option v-for="loc in locationArr"
                               :label="loc.name" :value="loc.name"></el-option>
                  </el-select>
                </el-form-item>
                <br>

                <el-form-item label="添加标签" prop="tags">
                  <el-input style="width: 600px" v-model="ruleForm.tags"
                            placeholder="请填写'#'开头的标签,例:#我的日常#萌宠..."></el-input>
                </el-form-item>
                <br>


                <el-form-item label="封面" prop="images">
                  <img v-if="isEdit" :src="ruleForm.images"
                       style="width: 200px;height: 200px;">
                  <el-upload
                      action="http://localhost:9090/v1/upload"
                      name="file"
                      :limit="1"
                      list-type="picture-card"
                      :on-success="handleSuccess"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">

                  </el-dialog>
                </el-form-item>
                <br>

                <!--<el-form-item v-show="c.type==2" label="文章视频">
                  <video v-if="isEdit" :src="c.videoUrl"
                         muted autoplay controls style="width: 200px; height: 150px;">
                    您的浏览器不支持播放此视频.
                  </video>
                  <el-upload style="width: 300px"
                             action="/v1/upload"
                             accept="video/mp4,video/x-m4v,video/*"
                             name="file"
                             limit="1"
                             :on-success="handleSuccess"
                             :on-preview="handlePictureCardPreview"
                             :on-remove="handleRemove">
                    <el-button type="primary">点击上传</el-button>
                    <div>只能上传mp4文件,且不超过100MB</div>
                  </el-upload>
                </el-form-item>-->

                <el-form-item label="文章内容" prop="content" :rules="contentRules">
                  <div style="border: 1px solid #ccc" >
                    <div id="wangEditor" v-model="ruleForm.content" @change="handleEditorChange"></div>
<!--                    <quill-editor
                        ref="myQuillEditor"
                        :options="editorOption"
                        @blur=""
                        @focus=""
                    ></quill-editor>-->
<!--                    <div id="toolbar-container" style="border-bottom: 1px solid #ccc;">&lt;!&ndash; 工具栏 &ndash;&gt;</div>-->
                    <div id="editor-container" ><!-- 编辑器 --></div>
                  </div>
                </el-form-item>


                <el-form-item>
                  <el-button type="primary" @click="submitForm('ruleForm')">发布</el-button>
                  <el-button type="primary" @click="resetForm">重置</el-button>
                </el-form-item>

              </el-form>
              <!--发布文章表单结束-->

            </el-card>
          </el-col>
        </el-row>
      </el-main>

    </el-container>
  </div>

<!--  <div>
    <quill-editor
        ref="myQuillEditor"
            :options="editorOption"
            @blur=""
            @focus=""
    ></quill-editor>
  </div>-->

</template>

<script>
/*import {quillEditor} from "vue-quill-editor";*/
import wangEditor from 'wangeditor';
export default {
  /*components:{
    quillEditor
  },*/
  name: "postArticle.vue",
  data(){
    return {
      //作者id
      userId:'',
      // 富文本编辑器
      editor: '',
      // 默认选中的选项卡名称
      activeTab: "1",
      //文章分类
      categoryOptions: [],
      //封面
      images:"",
      isEdit:false,
      dialogImageUrl: '',
      dialogVisible: false,
      //地点
      articleLocation:'',
      locationArr:[{id:1,name:'北京市'},{id:2,name:'上海市'},{id:3,name:'天津市'},{id:4,name:'重庆市'},{id:5,name:'黑龙江省'},{id:6,name:'辽宁省'},{id:7,name:'吉林省'},
        {id:8,name:'河北省'},{id:9,name:'河南省'},{id:10,name:'湖北省'},{id:11,name:'湖南省'},{id:12,name:'山东省'},{id:13,name:'山西省'},{id:14,name:'陕西省'},{id:15,name:'安徽省'},{id:16,name:'浙江省'},
        {id:17,name:'江苏省'},{id:18,name:'福建省'},{id:19,name:'广东省'},{id:20,name:'海南省'},{id:21,name:'四川省'},{id:22,name:'云南省'},{id:23,name:'贵州省'},{id:24,name:'青海省'},{id:25,name:'甘肃省'},
        {id:26,name:'江西省'},{id:27,name:'台湾省'},{id:28,name:'内蒙古自治区'},{id:29,name:'宁夏回族自治区'},{id:30,name:'新疆维吾尔自治区'},
        {id:31,name:'西藏自治区'},{id:32,name:'广西壮族自治区'},{id:33,name:'香港特别行政区'},{id:34,name:'澳门特别行政区'}],
      // 表单
      ruleForm: {
        title: '',
        images: '',
        articleLocation: '',
        categoriesId:'',
        tags: '',
        content:'',
        userId:'',
        editor:''
      },
      // 表单规则
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {pattern: /^[a-zA-Z\u4e00-\u9fa5]{2,10}$/, message: '文章标题必须是2~10长度的字符组成，且不能使用标点符号和数字', trigger: 'blur'}
        ],
        categoriesId: [
          {required: true, message: '请选择文章类别', trigger: 'change'}
        ],
        articleLocation: [
          {required: true, message: '请选择发布地点', trigger: 'change'}
        ],
        tags: [
          {pattern: /^(#([\u4e00-\u9fa5a-zA-Z]{1,10})){0,5}(?!#)$/, message: '文章标签必须为#开头且由1~10长度的中英文字符组成,最多添加5个标签', trigger: 'blur'}
        ],
        images: [
          {required: true, message: '请上传封面图片', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '请输入文章内容', trigger: 'blur'}
        ],
        userId:[],
        editor:[
          {required: true, message: '请输入文章内容', trigger: 'blur'}
        ]
      },
      contentRules: [
        { required: true, message: '文章内容不能为空', trigger: 'blur' }
      ]
    };
  },

  mounted() {
    this.initWangEditor();
    // 将默认选中的选项卡名称设置为"1"
    this.activeTab = "1";
    this.loadCategoryAll();




  },

  methods: {
    // 初始化富文本编辑器
    initWangEditor() {
      this.editor = new this.wangEditor('#wangEditor');
      this.editor.config.uploadImgHooks =
          { customInsert: function(insertImgFn, result) { insertImgFn(result.data.url); } }
      this.editor.config.zIndex = 1;
      this.editor.create();

    },

    // 上传成功后的回调
    /*handleUploadSuccess(response) {
      this.ruleForm.images = response.data.url;
    },*/

    handleSuccess(response, file, fileList) {
      console.log(file);
      if (file.raw.type.includes("image")){
        //把上传图片完成之后 得到的图片路径用变量记录
        this.ruleForm.images = "http://"+response.data;
        console.log(this.ruleForm.images);

        }
    },

    handleEditorChange() {
      // 编辑器内容改变时更新 ruleForm.content 的值
      // 可根据具体情况处理内容转换或其他逻辑
      console.log(this.ruleForm.content);
    },

    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:9090/v1/blogs/publish';
          console.log('url = ' + url);

          if (Array.isArray(this.ruleForm.categoriesId)) {
            this.ruleForm.categoriesId = this.ruleForm.categoriesId();
          }

          //设置作者id
          this.ruleForm.userId = localStorage.getItem("id");

          this.ruleForm.content = this.editor.txt.html();
          let formData = this.qs.stringify(this.ruleForm);
          console.log('formData = ' + formData);

          articleLocation: this.ruleForm.articleLocation,

          this.axios
              .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
              .post(url, formData).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.code == 200) {
              let message = '发布文章成功！';
              this.$alert(message, '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  this.resetForm(formName);

                }
              });
            } else {
              let message = jsonResult.message;
              this.$alert(message, '警告', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 重置表单
    resetForm() {
      this.$refs.ruleForm.resetFields();
      if (this.editor) {
        this.editor.txt.clear(); // 清空编辑器内容
      }
    },

    // 加载文章类别的数据
    loadCategoryAll() {
      let url = 'http://localhost:9090/v1/blogs/allCategories';
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        console.log(jsonResult)
        if (jsonResult.code == 200) {
          this.categoryOptions = jsonResult.data;
          console.log(this.categoryOptions);
        }
      });
    },
    //图片放大预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //删除图片
    handleRemove(file, fileList) {
      //判断删除的是图片还是视频
      if (file.raw.type.includes("image")){
        this.ruleForm.imgUrl="";
      }
      //发出删除文件的请求   file.response上传成功时服务器响应的内容ResultVO
      console.log(file.response);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get("http://localhost:9090/v1/upload/remove?url=" + file.response.data).then(function () {
        console.log("服务器文件删除完成!");
      })
    },
  },
}
</script>


<style scoped>

@media (max-width: 768px) {
  /* 在屏幕宽度小于等于 768px 时应用的样式 */
  body {
    font-size: 14px;
  }
}

@media (min-width: 769px) and (max-width: 1200px) {
  /* 在屏幕宽度在 769px 到 1200px 之间时应用的样式 */
  body {
    font-size: 16px;
  }
}

@media (min-width: 1201px) {
  /* 在屏幕宽度大于等于 1201px 时应用的样式 */
  body {
    font-size: 18px;
  }
}

.center{
  width: 1200px;
  margin: 0 auto;
}
#footer_center p{
  margin: 0;
}
#footer_center h3{
  color: white;
}
body{
  background-color: rgb(241,242,243);
}

</style>

